package tech.mhuang.pacebox.core.chain;

import java.util.List;

/**
 * 责任链实现
 *
 * @author mhuang
 * @since 1.0.0
 */
public class ChainAdapter<Request, Response> implements BaseChain<Request, Response> {

    private final List<BaseInterceptor<BaseChain<Request, Response>, Response>> interceptors;
    private final int index;
    private final Request request;

    public ChainAdapter(List<BaseInterceptor<BaseChain<Request, Response>, Response>> interceptors, int index, Request request) {
        this.interceptors = interceptors;
        this.index = index;
        this.request = request;
    }


    @Override
    public void add(BaseInterceptor<BaseChain<Request, Response>, Response> interceptor) {
        interceptors.add(interceptor);
    }

    @Override
    public void add(BaseInterceptor<BaseChain<Request, Response>, Response> interceptor, int index) {
        interceptors.add(index, interceptor);
    }

    @Override
    public void reset(List<BaseInterceptor<BaseChain<Request, Response>, Response>> baseInterceptors) {
        interceptors.clear();
        interceptors.addAll(baseInterceptors);
    }

    @Override
    public void reset() {
        interceptors.clear();
    }

    @Override
    public Request request() {
        return request;
    }

    @Override
    public Response proceed(Request request) {
        ChainAdapter<Request, Response> next = new ChainAdapter<>(interceptors, index + 1, request);
        BaseInterceptor<BaseChain<Request, Response>, Response> interceptor = interceptors.get(index);
        return interceptor.interceptor(next);
    }
}
